package cn.qyd.threadsignal;


import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * @author 邱运铎
 * @date 2024-03-18 21:29
 */
public class Mutex {
    private static class Syn extends AbstractQueuedSynchronizer {
        @Override
        protected boolean tryAcquire(int arg) {
            if (compareAndSetState(0,1)) {
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        @Override
        protected boolean tryRelease(int arg) {
            if (getState() == 0) {
                throw new IllegalMonitorStateException();
            }
            setExclusiveOwnerThread(null);
            setState(0);
            return true;
        }

        @Override
        protected boolean isHeldExclusively() {
            return getState() == 1;
        }
    }

    private final Syn syn = new Syn();

    public void lock() {
        syn.acquire(1);
    }

    public void unlock() {
        syn.tryRelease(1);
    }

    public boolean isLocked() {
        return syn.isHeldExclusively();
    }
}
